package com.dynamic.sync.toolkit.mongo;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.dynamic.sync.toolkit.EnvType;
import com.dynamic.sync.toolkit.mongo.property.MongoPropertyManager;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

/**
 * @author ZonLen since on 2021/6/18 下午5:08
 */
@Component
public class MongoClientProvider {

  public static final Map<EnvType, MongoClient> ENV_MONGO_CLIENT_CACHE = new ConcurrentHashMap<>();

  @Autowired
  private MongoPropertyManager mongoPropertyManager;

  @Autowired
  private MongoTemplate mongoTemplate;

  private MongoClient mongoClient(EnvType envType) {
    MongoClient client = ENV_MONGO_CLIENT_CACHE.get(envType);
    if (client == null) {
      client = MongoClients.create(mongoPropertyManager.uri(envType));
      ENV_MONGO_CLIENT_CACHE.putIfAbsent(envType, client);
    }
    return client;
  }

  public MongoDatabase mongoDatabase(EnvType envType) {
//    if (EnvType.local == envType){
//      return mongoTemplate.getDb();
//    }
    final MongoClient mongoClient = mongoClient(envType);
    return mongoClient.getDatabase(mongoPropertyManager.database(envType));
  }


}
